package com.shj.em.biz.sell.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.shj.em.aa.entity.User;
import com.shj.em.base.controller.BaseController;
import com.shj.em.base.support.ResMsg;
import com.shj.em.base.vo.PageVO;
import com.shj.em.biz.Constants;
import com.shj.em.biz.company.entity.Company;
import com.shj.em.biz.company.entity.Contact;
import com.shj.em.biz.sell.dto.OrderEditInitDTO;
import com.shj.em.biz.sell.dto.OrderInitDTO;
import com.shj.em.biz.sell.dto.OrderSearchDTO;
import com.shj.em.biz.sell.dto.QuotSearchPageInitDTO;
import com.shj.em.biz.sell.entity.Order;
import com.shj.em.biz.sell.service.OrderItemService;
import com.shj.em.biz.sys.entity.Cd;
import com.shj.em.biz.sys.service.CdService;
import com.shj.em.common.annotation.Log;
import com.shj.em.util.ShiroUtils;
import com.shj.em.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 订单信息 前端控制器
 * </p>
 *
 * @author Shen Huang Jian
 * @since 2018-07-09
 */
@RestController
@Slf4j
@RequestMapping("/sell/order")
public class OrderController extends BaseController<Order>{

    @Autowired
    OrderItemService orderItemService;

    @GetMapping("/loadInitPageData")
    public ResMsg<OrderInitDTO> loadInitPageData(){
        boolean isManager = ShiroUtils.isManager();
        boolean isSuper = ShiroUtils.isSuperAdmin();
        //boolean isFinance = ShiroUtils.isFinancial();
        OrderInitDTO initDTO = new OrderInitDTO();

        List<Company> companyList = null;
        if(isManager || isSuper){
            companyList = companyService.getAllCustomers();
        }else{
            companyList = companyService.getCustomersBySellMan(ShiroUtils.getUserId());
        }

        List<User> sells = userService.getUsersByRoleId(Constants.ROLE_SELL);
        initDTO.setSells(sells);

        initDTO.setCustomers(companyList);

        List<Cd> statusList = cdService.queryCdsByType(CdService.CD_ORDER_STATUS);
        initDTO.setStatusList(statusList);

        List<Cd> receipts = cdService.queryCdsByType(CdService.CD_RECEIPT_COMP);
        initDTO.setReceiptCompanies(receipts);

        List<Cd> units = cdService.queryCdsByType(CdService.CD_TYPE_UNIT);
        initDTO.setUnits(units);

        boolean canCloseOrder = ShiroUtils.hasPermission("order:close");
        initDTO.setCanCloseOrder(canCloseOrder);

        return ResMsg.ok(initDTO);
    }

    @GetMapping("/list")
    public PageVO<Order> list(OrderSearchDTO orderSearchDTO){
        boolean isManager = ShiroUtils.isManager();
        boolean isSuper = ShiroUtils.isSuperAdmin();
        boolean isFinance = ShiroUtils.isFinancial();
        boolean isPurchase = ShiroUtils.isPurchase();
        boolean isSupply = ShiroUtils.isSupply();
        boolean isProd = ShiroUtils.isProd();

        if(StringUtils.isBlank(orderSearchDTO.getSellMan())){// 某些查询含有业务员的查询条件
            // 现在只对 sell 做过滤。没有直接使用 sell 做过滤，是因为如果某个人同时有
            // sell 和 其它角色时，只能看到部分订单
            if(!isManager && !isSuper && !isFinance && !isPurchase && !isSupply &&!isProd){
                orderSearchDTO.setSellMan(ShiroUtils.getUserId());
            }
        }

        Page<Order> page = orderService.queryOrderPage(orderSearchDTO);
        PageVO<Order> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setRows(page.getRecords());
        return pageVO;
    }

    @GetMapping("/{id}")
    public ResMsg<OrderEditInitDTO> findOrderById(@PathVariable("id") Long id){
        boolean isEdit = id > -1L;
        OrderEditInitDTO initDTO = new OrderEditInitDTO();
        Order order = isEdit ? orderService.selectById(id) : new Order();
        initDTO.setOrder(order);

        if(isEdit){
            initDTO.setOrderItems(orderItemService.getItemsByOrderId(id));
            if(order.getCustId() != null){
                List<Contact> contacts = contactService.findContactsByCompanyId(order.getCustId());
                initDTO.setContactList(contacts);
            }
        }else{
            order.setOrderDt(new Date());
            order.setSellMan(ShiroUtils.getUserId());
        }

        return ResMsg.ok(initDTO);
    }

    @Log("创建订单信息")
    @PostMapping
    public ResMsg add(@RequestBody Order order){
        long id = orderService.createOrder(order);
        return ResMsg.ok(id);
    }

    @Log("更新订单信息")
    @PutMapping
    public ResMsg edit(@RequestBody Order order){
        orderService.updateOrder(order);
        return ResMsg.ok();
    }

    @Log("批量删除订单")
    @DeleteMapping
    public ResMsg batchRemove(@RequestBody Long[] ids){
        orderService.deleteBatchIds(Arrays.asList(ids));
        return ResMsg.ok();
    }

    @Log("复制订单")
    @PutMapping("/copy/{id}")
    public ResMsg copyOrder(@PathVariable("id")  Long id){
        Order order = orderService.copyOrder(id);
        return ResMsg.ok(order.getId());
    }

    @Log("关闭订单")
    @PutMapping("/close/{id}")
    @ResponseBody
    public ResMsg closeOrder(@PathVariable("id") Long id){
        orderService.closeOrder(id);
        return ResMsg.ok();
    }

}

